<?php

namespace App\Http\Controllers\Admin;

use Validator;
use Illuminate\Http\Request;
use App\Model\AdminLogsModel;
use App\Model\ShopAttrValModel;
use App\Model\ShopAttrKeyModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;


class ShopAttrValController extends Controller
{
    public function index(Request $request)
    {

        $results = ShopAttrValModel::where('attr_key_id',$request->id)->get();
        $lists= ShopAttrKeyModel::where('id',$request->id)->first();

        return view('admin.attr_val.add')->with(["results"=>$results,"lists"=>$lists]);
    }

    //添加
    public function insert(Request $request)
    {
    	$post = $request->post();
	  	$validator = Validator::make($post,[
			'vname'=>'required',
		  
	  	],[
			'vname.required' => '规格名不能为空',
		 
	  	]);
	  	if($validator->fails()){
			return returnJson(0, $validator->errors()->first());
	  	}
		$attrs = ShopAttrKeyModel::where('id',request()->attr_key_id)->first();
	  	if(ShopAttrValModel::where('attr_key_id',request()->attr_key_id)->where('vname',request()->vname)->first()){
			return returnJson(0, '该规格属性已存在');
		}
	  	DB::beginTransaction();
	  	try {
			$attrval = New ShopAttrValModel();
			$attrval -> attr_key_id = request() -> attr_key_id;
			$attrval -> vname = request() -> vname;
			$attrval -> save();
			DB::commit();

	  	} catch (Exception $e) {
			DB::rollBack();
			throw $e;			
			return returnJson(0,'操作失败,请稍后再试');
	  	}
	  	$msg = '规格【'.$attrs['kname'].'】(id:'.request()->attr_key_id.')增加属性值:'.request()->vname;
	  	AdminLogsModel::addLog($msg);
	  	 return returnJson(1,'添加成功');
//	  	return redirect('/admin/attrval/index?id='.request() -> attr_key_id)->with('1', '添加成功');
    }

    public function del(Request $request)
    {
    	//return "aaa";
		//属性信息
		$vals = ShopAttrValModel::where('id',$request->id)->first();
		//规格类型信息
		$keys = ShopAttrKeyModel::where('id',$vals['attr_key_id'])->first();
    	if(ShopAttrValModel::where('id',$request->id)->delete()){
			$msg = '规格【'.$keys['kname'].'】(id:'.request()->attr_key_id.')删除属性值:'.$vals['vname'];
			AdminLogsModel::addLog($msg);
			return returnJson(1, '删除成功');
		}else{
			return returnJson(0, '删除失败');
		}

    }

}
